package idor

import (
	"database/sql"
	"html"
	"regexp"

	"github.com/govwa/util/database"
)

var DB *sql.DB
var err error

/*func init(){
	DB, err = database.Connect()
	if err != nil{
		log.Println(err.Error())
	}
}*/

type Profile struct {
	Uid         int
	Name        string
	City        string
	PhoneNumber string
}

func NewProfile() *Profile {
	return &Profile{}
}

func (p *Profile) GetData(uid string) error {

	/* this funciton use to get data Profile from database with prepare statement */
	DB, err = database.Connect()
	const (
		getProfileSql = `SELECT p.user_id, p.full_name, p.city, p.phone_number 
		FROM Profile as p,Users as u 
		where p.user_id = u.id 
		and u.id=?`
	)

	stmt, err := DB.Prepare(getProfileSql) //prepare statement
	if err != nil {
		return err
	}

	defer stmt.Close()
	err = stmt.QueryRow(uid).Scan(&p.Uid, &p.Name, &p.City, &p.PhoneNumber)
	if err != nil {
		return err
	}
	return nil
}

func (p *Profile) UpdateProfile(name, city, phoneNumber, uid string) error {
	DB, err = database.Connect()
	const (
		sql = `UPDATE Profile 
		set full_name=?, 
		city=?, 
		phone_number=? 
		where user_id=?`
	)

	stmt, err := DB.Prepare(sql)
	if err != nil {
		return err
	}
	res, err := stmt.Exec(name, city, phoneNumber, uid)
	if err != nil {
		return err
	}
	_, err = res.RowsAffected()

	if err != nil {
		return err
	}
	return nil
}

func HTMLEscapeString(text string) string {
	filter := regexp.MustCompile("<[^>]*>")
	output := filter.ReplaceAllString(text, "")
	return html.EscapeString(output)
}
